from fastapi import APIRouter, HTTPException, BackgroundTasks
from fastapi.responses import StreamingResponse
from sse_starlette.sse import EventSourceResponse
import json
import logging
from typing import AsyncGenerator

from models.chat_models import ChatRequest, ChatResponse, TTSRequest
from services.qwen_poet_service import QwenPoetService
from backend.config.poets_knowledge import get_poet_voices, get_all_poets, get_poet_knowledge

logger = logging.getLogger(__name__)

# 创建诗人专用路由器
router = APIRouter(prefix="/api/qwen-poet", tags=["qwen-poet"])

# 初始化诗人专用服务
qwen_poet_service = QwenPoetService()

@router.post("/chat", response_model=ChatResponse)
async def chat_with_poet(request: ChatRequest):
    """
    诗人专用对话接口
    
    Args:
        request: 聊天请求
        
    Returns:
        ChatResponse: 完整的诗人聊天响应
    """
    try:
        logger.info(f"收到诗人对话请求: {request.message}")
        
        # 如果请求中指定了诗人，则切换诗人
        if request.poet_id:
            qwen_poet_service.set_poet(request.poet_id)
        
        # 1. 生成诗人回复
        reply_text = await qwen_poet_service.generate_poet_response(
            message=request.message
        )
        
        # 2. 分析诗人回复的情感
        emotion = await qwen_poet_service.analyze_poet_emotion(reply_text)
        
        # 3. 生成诗人风格的语音
        audio_url = None
        duration = None
        timestamps = None
        audio_error = None
        
        try:
            # 为不同诗人选择合适的语音
            voice = "zhichu"  # 默认女声
            if qwen_poet_service.current_poet in ["libai", "dufu", "sushi"]:
                voice = "zhizheng"  # 男声音色
            
            audio_url, duration, timestamps = await qwen_poet_service.synthesize_poet_speech(
                text=reply_text,
                voice=voice
            )
            logger.info("诗人语音合成成功")
        except Exception as e:
            audio_error = str(e)
            logger.warning(f"诗人语音合成失败，将返回纯文本回复: {audio_error}")
        
        # 4. 构建响应
        response = ChatResponse(
            reply=reply_text,
            audio_url=audio_url,
            animation="",  # 可以根据诗人特点设置默认动画
            emotion=emotion,
            duration=duration,
            timestamps=timestamps,
            poet_id=qwen_poet_service.current_poet,
            poet_name=qwen_poet_service.get_poet_info()["name"]
        )
        
        # 如果音频生成失败，在日志中记录但不影响主要功能
        if audio_error:
            logger.info(f"诗人聊天处理完成（无音频）: {response.reply[:50]}...")
        else:
            logger.info(f"诗人聊天处理完成（含音频）: {response.reply[:50]}...")
        
        return response
        
    except Exception as e:
        logger.error(f"诗人对话处理失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"诗人对话处理失败: {str(e)}")

@router.post("/chat/stream")
async def chat_poet_stream(request: ChatRequest):
    """
    诗人专用流式对话接口，支持Server-Sent Events
    
    Args:
        request: 聊天请求
        
    Returns:
        EventSourceResponse: 流式响应
    """
    try:
        # 如果请求中指定了诗人，则切换诗人
        if request.poet_id:
            qwen_poet_service.set_poet(request.poet_id)
        
        async def generate_stream() -> AsyncGenerator[str, None]:
            try:
                async for chunk in qwen_poet_service.generate_poet_response_stream(request.message):
                    # 添加诗人信息到流式响应
                    chunk_with_poet = {
                        **chunk,
                        "poet_id": qwen_poet_service.current_poet,
                        "poet_name": qwen_poet_service.get_poet_info()["name"]
                    }
                    yield f"data: {json.dumps(chunk_with_poet, ensure_ascii=False)}\n\n"
            except Exception as e:
                logger.error(f"诗人流式对话失败: {str(e)}")
                yield f"data: {json.dumps({'type': 'error', 'message': str(e)}, ensure_ascii=False)}\n\n"
        
        return EventSourceResponse(generate_stream())
        
    except Exception as e:
        logger.error(f"创建诗人流式响应失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"创建诗人流式响应失败: {str(e)}")

@router.post("/tts")
async def poet_text_to_speech(request: TTSRequest, background_tasks: BackgroundTasks):
    """
    诗人专用文本转语音接口
    
    Args:
        request: TTS请求
        background_tasks: 后台任务
        
    Returns:
        dict: 包含音频URL和时长的响应
    """
    try:
        logger.info(f"收到诗人TTS请求: {request.text[:50]}...")
        
        # 如果请求中指定了诗人，则切换诗人
        if request.poet_id:
            qwen_poet_service.set_poet(request.poet_id)
        
        # 为不同诗人选择合适的语音
        voice = request.voice
        if not voice:
            voice = "zhichu"  # 默认女声
            if qwen_poet_service.current_poet in ["libai", "dufu", "sushi"]:
                voice = "zhizheng"  # 男声音色
        
        audio_url, duration, _ = await qwen_poet_service.synthesize_poet_speech(
            text=request.text,
            voice=voice
        )
        
        return {
            "audio_url": audio_url,
            "duration": duration,
            "text": request.text,
            "poet_id": qwen_poet_service.current_poet,
            "voice": voice
        }
        
    except Exception as e:
        logger.error(f"诗人TTS处理失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"诗人语音合成失败: {str(e)}")

@router.get("/poets")
async def get_all_poets_info():
    """
    获取所有可用诗人的信息
    
    Returns:
        dict: 包含所有诗人信息的字典
    """
    try:
        poets = get_all_poets()
        return {
            "poets": poets,
            "total": len(poets)
        }
    except Exception as e:
        logger.error(f"获取诗人列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取诗人列表失败: {str(e)}")

@router.get("/poets/{poet_id}")
async def get_poet_detail(poet_id: str):
    """
    获取特定诗人的详细信息
    
    Args:
        poet_id: 诗人ID
        
    Returns:
        dict: 诗人详细信息
    """
    try:
        poet_info = get_poet_knowledge(poet_id)
        if not poet_info:
            raise HTTPException(status_code=404, detail=f"未找到诗人: {poet_id}")
        
        return poet_info
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取诗人详情失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取诗人详情失败: {str(e)}")

@router.post("/set-poet/{poet_id}")
async def set_current_poet(poet_id: str):
    """
    设置当前使用的诗人
    
    Args:
        poet_id: 诗人ID
        
    Returns:
        dict: 操作结果
    """
    try:
        # 检查诗人是否存在
        poet_info = get_poet_knowledge(poet_id)
        if not poet_info:
            raise HTTPException(status_code=404, detail=f"未找到诗人: {poet_id}")
        
        # 设置当前诗人
        qwen_poet_service.set_poet(poet_id)
        
        return {
            "success": True,
            "message": f"已切换到诗人: {poet_info['name']}",
            "poet_id": poet_id,
            "poet_name": poet_info['name']
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"切换诗人失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"切换诗人失败: {str(e)}")

@router.get("/current-poet")
async def get_current_poet_info():
    """
    获取当前使用的诗人信息
    
    Returns:
        dict: 当前诗人信息
    """
    try:
        poet_info = qwen_poet_service.get_poet_info()
        return {
            "current_poet": poet_info,
            "message": f"当前使用诗人: {poet_info['name']}"
        }
    except Exception as e:
        logger.error(f"获取当前诗人信息失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取当前诗人信息失败: {str(e)}")

@router.post("/generate-poem")
async def generate_poem(request: dict):
    """
    生成特定主题的诗歌
    
    Args:
        request: 包含主题、诗人ID等信息的请求体
        
    Returns:
        dict: 包含生成诗歌的响应
    """
    try:
        theme = request.get("theme", "")
        poet_id = request.get("poet_id", None)
        
        if not theme:
            raise HTTPException(status_code=400, detail="请提供诗歌主题")
        
        # 如果指定了诗人，则切换诗人
        if poet_id:
            qwen_poet_service.set_poet(poet_id)
        
        # 构建诗歌生成提示
        poet_name = qwen_poet_service.get_poet_info()["name"]
        poem_prompt = f"以'{theme}'为主题，模仿{poet_name}的风格创作一首诗歌。请确保诗歌符合{poet_name}的语言特点和创作风格。"
        
        logger.info(f"生成诗歌请求: 主题={theme}, 诗人={poet_name}")
        
        # 生成诗歌
        poem = await qwen_poet_service.generate_poet_response(poem_prompt)
        
        return {
            "poem": poem,
            "theme": theme,
            "poet_id": qwen_poet_service.current_poet,
            "poet_name": poet_name,
            "success": True
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"诗歌生成失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"诗歌生成失败: {str(e)}")

@router.get("/voices")
async def get_poet_voice_options():
    """
    获取诗人专用的语音选项
    
    Returns:
        dict: 可用语音选项
    """
    try:
        # 获取诗人专用的语音列表
        voices = get_poet_voices()
        
        # 如果没有专门的诗人语音列表，则返回默认语音选项
        if not voices:
            voices = {
                "zhichu": {"name": "知初", "gender": "female", "description": "温柔优雅的女声，适合李清照等女诗人"},
                "zhizheng": {"name": "知正", "gender": "male", "description": "沉稳有力的男声，适合李白、杜甫、苏轼等男诗人"}
            }
        
        return {
            "voices": voices,
            "total": len(voices)
        }
    except Exception as e:
        logger.error(f"获取诗人语音选项失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取诗人语音选项失败: {str(e)}")